//
//  SAStatisticsProfitDetailVC.m
//  saasRetail
//
//  Created by mac on 2022/7/28.
//

#import "SAStatisticsProfitDetailVC.h"
#import "SAStockProfitLossDetailAPI.h"
#import "YBImageBrowser.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "ScanHelper.h"
#import "SAWarehousingDetailCell.h"
#import "SASalesOrderViewListModel.h"
#import "SASaleDocumentsHeaderView.h"
#import "SAStatisticsProfitDetailModel.h"

@interface SAStatisticsProfitDetailVC ()<UITableViewDelegate, UITableViewDataSource, HTTPAPIDelegate, UITextFieldDelegate, YBImageBrowserDataSource>

@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UITextField *searchTf;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *scanBtn;
@property (nonatomic, strong) SAStockProfitLossDetailAPI *stockProfitLossDetailAPI;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, strong) NSString *checkOrderId;
@property (nonatomic, strong) UIView *tipView;
@property (nonatomic, strong) NSArray *imageList;
@property (nonatomic, strong) NSMutableArray<SASalesOrderViewListModel *> *dataMarr;
@property (nonatomic, strong) UILabel *checkLab;

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UILabel *totalBeforeStockLab;
@property (nonatomic, strong) UILabel *totalAfterStockLab;
@property (nonatomic, strong) UILabel *totalDiffStockLab;

@end

@implementation SAStatisticsProfitDetailVC

-(instancetype)initWithCheckOrderId:(NSString *)checkOrderId {
    if (self = [super init]) {
        self.checkOrderId = checkOrderId;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    if (self.stockProfitLossDetailAPI == api) {
        if (self.currentPage == 1) {
            [self.dataMarr removeAllObjects];
            SAStatisticsProfitObjModel *objModel = [SAStatisticsProfitObjModel mj_objectWithKeyValues:data[@"data"][@"obj"]];
            _checkLab.text = [NSString stringWithFormat:@"盘点单号：PD%@，关联流水号：%@",objModel.checkOrderNo,objModel.checkFlowNo];
            self.totalBeforeStockLab.text = objModel.totalBeforeStock;
            self.totalAfterStockLab.text = objModel.totalAfterStock;
            self.totalDiffStockLab.text = objModel.totalDiffStock;
        }
        NSMutableArray<SAStatisticsProfitDetailModel *> *marr = [SAStatisticsProfitDetailModel mj_objectArrayWithKeyValuesArray:data[@"data"][@"records"]];
        
        NSMutableArray *idMarr = [NSMutableArray array];
        for (SAStatisticsProfitDetailModel *model in marr) {
            if (![idMarr containsObject:model.productId]) {
                [idMarr addObject:model.productId];
            }
        }
        
        for (NSString *productId in idMarr) {
            SASalesOrderViewListModel *productModel = [SASalesOrderViewListModel new];
            productModel.productId = productId;
            NSMutableArray <SASalesOrderToPendSkuList *>*toPendSkuAttrs = [NSMutableArray array];
            productModel.toPendSkuAttrs = toPendSkuAttrs;
            for (SAStatisticsProfitDetailModel *model in marr) {
                if ([productId isEqualToString:model.productId]) {
                    productModel.productName = model.productName;
                    productModel.productCode = model.productCode;
                    productModel.imgList = model.imgList;
                    if (productModel.imgList.count > 0) {
                        productModel.img = productModel.imgList[0];
                    }
                    SASalesOrderToPendSkuList *sku = [[SASalesOrderToPendSkuList alloc] init];
                    sku.count = model.beforeStock;
                    sku.stock = model.afterStock;
                    sku.subtotal = model.diffStock;
                    sku.colourId = model.colourId;
                    sku.colourName = model.colourName;
                    sku.sizeId = model.sizeId;
                    sku.sizeName = model.sizeName;
                    [toPendSkuAttrs addObject:sku];
                }
            }
            [self.dataMarr addObject:productModel];
        }
        [self.tableView reloadData];
        self.tipView.hidden = self.dataMarr.count > 0;
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}

#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataMarr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataMarr[section].toPendSkuAttrs.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SAWarehousingDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SAWarehousingDetailCell" forIndexPath:indexPath];
    SASalesOrderToPendSkuList *model = self.dataMarr[indexPath.section].toPendSkuAttrs[indexPath.row];
    cell.productModel = model;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(40);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    SASaleDocumentsHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SASaleDocumentsHeaderView"];
    SASalesOrderViewListModel *model = self.dataMarr[section];
    header.saleModel = model;
    WeakSelf
    header.imageBlock = ^{
        [weakSelf showImage:model.imgList];
    };
    return header;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScaleNum(40);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return kScaleNum(0.5);
}

-(void)showImage:(NSArray *)imageList {
    self.imageList = imageList;
    if (self.imageList.count > 0) {
        NSMutableArray *imageMarr = [NSMutableArray array];
        for (NSString *url in self.imageList) {
            NSString *newUrl = [url stringByReplacingOccurrencesOfString:@"?x-oss-process=style/thumbnail" withString:@""];
            NSString *imageUrl = [NSString stringWithFormat:@"%@?x-oss-process=image/resize,l_720",newUrl];
            [imageMarr addObject:imageUrl];
        }
        self.imageList = imageMarr;
        YBImageBrowser *browser = [YBImageBrowser new];
        browser.dataSourceArray = self.imageList;
        browser.dataSource = self;
        browser.currentPage = 0;
        [browser show];
    }else {
        [Prompt popPromptViewWithMsg:@"该商品没有图片" duration:2];
    }
}

//YBImageBrowserDataSource 代理实现赋值数据
- (NSInteger)yb_numberOfCellsInImageBrowser:(YBImageBrowser *)imageBrowser {
    return self.imageList.count;
}

- (id<YBIBDataProtocol>)yb_imageBrowser:(YBImageBrowser *)imageBrowser dataForCellAtIndex:(NSInteger)index {
    NSString *urlStr = [self.imageList objectAtIndex:index];
    YBIBImageData *data = [YBIBImageData new];
    data.imageURL = [NSURL URLWithString:urlStr];
    return data;
}

#pragma mark - UITextField
- (void)textFieldEditChanged:(UITextField *)textField {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(searchProduct:) object:textField];
    [self performSelector:@selector(searchProduct:) withObject:textField afterDelay:0.3];
}

- (void)searchProduct:(UITextField *)textField {
    self.currentPage = 1;
    [self loadData];
}

#pragma mark - event
-(void)loadData {
    self.stockProfitLossDetailAPI.currentPage = self.currentPage;
    self.stockProfitLossDetailAPI.productNameOrCode = self.searchTf.text;
    [self.stockProfitLossDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
}

-(void)clickedScanBtn {
    [self.view endEditing:YES];
    [self.navigationController pushViewController:[[ScanHelper shareInstance] ScanVCWithStyle:notSquare qrResultCallBack:^(id result) {
        //扫码结果
        self.searchTf.text = result;
        self.currentPage = 1;
        [self loadData];
        [self.navigationController popViewControllerAnimated:NO];
    }] animated:YES];
}

#pragma mark - initUI
-(void)initUI {
    [self setNavigationItemBackBBIAndTitle:@""];
    [self setBgImage:nil];
    self.view.backgroundColor = [UIColor whiteColor];
    [self addRightViews:@[self.topView]];
    [self.topView addSubview:self.searchTf];
    [self.topView addSubview:self.scanBtn];
    
    [self.view addSubview:self.checkLab];
    [self.checkLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(kScaleNum(StatusHeight + 7));
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
    }];
    
    UIView *grayView = [[UIView alloc] init];
    grayView.backgroundColor = kTextBgColor;
    [self.view addSubview:grayView];
    [grayView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.checkLab.mas_bottom).offset(kScaleNum(7));
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(kScaleNum(35));
    }];

    NSArray *arr2 = @[@"商品", @"盘前", @"盘后", @"盈亏数"];
    for (int i = 0; i < arr2.count; i++) {
        UILabel *titleLab = [[UILabel alloc] init];
        titleLab.text = arr2[i];
        titleLab.font = kFont(15);
        titleLab.textColor = kGrayColor;
        [grayView addSubview:titleLab];
        titleLab.textAlignment = NSTextAlignmentCenter;
        if (i == 0) {
            titleLab.frame = CGRectMake(kScaleNum(20), 0, kScaleNum(60), kScaleNum(35));
            titleLab.textAlignment = NSTextAlignmentLeft;
        }else if (i == 1) {
            titleLab.frame = CGRectMake(kScaleNum(150), 0, kScaleNum(70), kScaleNum(35));
        }else if (i == 2) {
            titleLab.frame = CGRectMake(kScaleNum(225), 0, kScaleNum(70), kScaleNum(35));
        }else if (i == 3) {
            titleLab.frame = CGRectMake(kScaleNum(300), 0, kScaleNum(70), kScaleNum(35));
        }
    }
    
    UIView *bottomView = [[UIView alloc] init];
    bottomView.backgroundColor = kTextBgColor;
    [self.view addSubview:bottomView];
    self.bottomView = bottomView;
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-SafeFooterHeight);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(kScaleNum(35));
    }];
    
    for (int i = 0; i < 4; i++) {
        UILabel *titleLab = [[UILabel alloc] init];
        titleLab.text = @"合计";
        titleLab.font = kFont(15);
        titleLab.textColor = kGrayColor;
        [bottomView addSubview:titleLab];
        titleLab.textAlignment = NSTextAlignmentCenter;
        if (i == 0) {
            titleLab.frame = CGRectMake(kScaleNum(20), 0, kScaleNum(60), kScaleNum(35));
            titleLab.textAlignment = NSTextAlignmentLeft;
        }else if (i == 1) {
            titleLab.frame = CGRectMake(kScaleNum(150), 0, kScaleNum(70), kScaleNum(35));
            self.totalBeforeStockLab = titleLab;
        }else if (i == 2) {
            titleLab.frame = CGRectMake(kScaleNum(225), 0, kScaleNum(70), kScaleNum(35));
            self.totalAfterStockLab = titleLab;
        }else if (i == 3) {
            titleLab.frame = CGRectMake(kScaleNum(300), 0, kScaleNum(70), kScaleNum(35));
            self.totalDiffStockLab = titleLab;
        }
    }
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(grayView.mas_bottom);
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-SafeFooterHeight - kScaleNum(35));
    }];
    
    [self.view addSubview:self.tipView];
    [self.tipView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(grayView.mas_bottom);
        make.left.right.bottom.mas_equalTo(0);
    }];
    
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf.view endEditing:YES];
        weakSelf.currentPage = 1;
        [weakSelf loadData];
    }];
    MJRefreshAutoStateFooter *mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        [weakSelf.view endEditing:YES];
        weakSelf.currentPage ++;
        [weakSelf loadData];
    }];
    [mj_footer setTitle:@"已经到底啦~" forState:MJRefreshStateIdle];//设置闲置状态下不显示“点击或上拉加载更多”
    self.tableView.mj_footer = mj_footer;

    
    self.currentPage = 1;
    self.stockProfitLossDetailAPI.pageSize = 20;
    self.stockProfitLossDetailAPI.checkOrderId = self.checkOrderId;
    self.stockProfitLossDetailAPI.showDiff = @"1";
    [self loadData];
}

#pragma mark - lazy
-(UIView *)topView {
    if (!_topView) {
        _topView = [[UIView alloc] initWithFrame:SARectMake(0, 0, kBaseScreenWidth - 50, 44)];
    }
    return _topView;
}

-(UIButton *)scanBtn {
    if (!_scanBtn) {
        _scanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _scanBtn.frame = SARectMake(0, 0, 30, 44);
        [_scanBtn setImage:[UIImage imageNamed:@"home_scan"] forState:UIControlStateNormal];
        [_scanBtn addTarget:self action:@selector(clickedScanBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _scanBtn;
}

-(UITextField *)searchTf {
    if (!_searchTf) {
        _searchTf = [[UITextField alloc] initWithFrame:SARectMake(45, 7, 220, 30)];
        _searchTf.placeholder = @"输入商品款号/名称/条码";
        _searchTf.backgroundColor = [UIColor whiteColor];
        _searchTf.layer.cornerRadius = kScaleNum(5);
        _searchTf.layer.masksToBounds = YES;
        _searchTf.delegate = self;
        _searchTf.font = kFont(14);
        _searchTf.clearButtonMode = UITextFieldViewModeWhileEditing;
        UIView *leftView = [[UIView alloc] initWithFrame:SARectMake(0, 0, 26, 30)];
        UIImageView *imageV = [[UIImageView alloc] initWithFrame:SARectMake(6, 7, 14, 16)];
        imageV.image = [UIImage imageNamed:@"shop_search"];
        [leftView addSubview:imageV];
        _searchTf.leftView = leftView;
        _searchTf.leftViewMode = UITextFieldViewModeAlways;
        [_searchTf addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    }
    return _searchTf;
}

-(UILabel *)checkLab {
    if (!_checkLab) {
        _checkLab = [[UILabel alloc] init];
        _checkLab.text = [NSString stringWithFormat:@"盘点单号：PD%@",self.checkOrderId];
        _checkLab.font = kFont(15);
        _checkLab.textColor = kBlackColor;
        _checkLab.numberOfLines = 0;
    }
    return _checkLab;
}

-(SAStockProfitLossDetailAPI *)stockProfitLossDetailAPI {
    if (!_stockProfitLossDetailAPI) {
        _stockProfitLossDetailAPI = [SAStockProfitLossDetailAPI apiWithDelegate:self];
    }
    return _stockProfitLossDetailAPI;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = kLineColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SASaleDocumentsHeaderView class] forHeaderFooterViewReuseIdentifier:@"SASaleDocumentsHeaderView"];
        [_tableView registerClass:[SAWarehousingDetailCell class] forCellReuseIdentifier:@"SAWarehousingDetailCell"];
    }
    return _tableView;
}

-(UIView *)tipView {
    if (!_tipView) {
        _tipView = [[UIView alloc] init];
        _tipView.backgroundColor = [UIColor whiteColor];
        UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Shop_search2"]];
        icon.frame = SARectMake(124, 106, 138, 83);
        [_tipView addSubview:icon];
        UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, icon.maxY + kScaleNum(20), _tipView.width, kScaleNum(20))];
        titleLab.text = @"暂无相关信息";
        titleLab.textAlignment = NSTextAlignmentCenter;
        titleLab.textColor = kGrayColor;
        [_tipView addSubview:titleLab];
    }
    return _tipView;
}

-(NSMutableArray<SASalesOrderViewListModel *> *)dataMarr {
    if (!_dataMarr) {
        _dataMarr = [NSMutableArray array];
    }
    return _dataMarr;
}

@end
